import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUserStore } from "@/stores/user";
import { useAppStore } from "@/stores/app";
import router from "@/router";
import { API_CONFIG, HTTP_STATUS, ERROR_CODES } from "./config";

// API响应接口
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
  timestamp: number;
  traceId?: string;
}

// 分页响应接口
export interface PageResponse<T = any> {
  content: T[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
  first: boolean;
  last: boolean;
  empty: boolean;
}

// 请求配置
const config: AxiosRequestConfig = {
  baseURL: API_CONFIG.BASE_URL,
  timeout: API_CONFIG.TIMEOUT,
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
};

// 创建axios实例
const service: AxiosInstance = axios.create(config);

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    const appStore = useAppStore();

    // 添加认证token
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`;
    }

    // 添加请求ID用于追踪
    config.headers["X-Request-ID"] =
      `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    // 添加用户代理信息
    config.headers["X-Client-Version"] = appStore.appConfig.version;
    config.headers["X-Client-Platform"] = appStore.deviceType;

    // 显示加载状态
    if (config.showLoading !== false) {
      appStore.setLoading(true, config.loadingText || "请求中...");
    }

    // 开发环境下记录API请求信息
    // console.log(`🚀 API请求: ${config.method?.toUpperCase()} ${config.url}`, {
    //   params: config.params,
    //   data: config.data
    // })

    return config;
  },
  (error) => {
    const appStore = useAppStore();
    appStore.setLoading(false);

    // 请求拦截器错误处理
    // console.error('❌ 请求拦截器错误:', error)
    return Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  async (response: AxiosResponse<ApiResponse>) => {
    const appStore = useAppStore();
    appStore.setLoading(false);

    const { data } = response;

    // 开发环境下记录API响应信息
    // console.log(`✅ API响应: ${response.config.method?.toUpperCase()} ${response.config.url}`, {
    //   status: response.status,
    //   data: data
    // })

    // 检查业务状态码
    if (data.code === HTTP_STATUS.OK) {
      return data.data;
    }

    // 处理业务错误
    const errorMessage = data.message || "请求失败";

    // 特殊错误码处理
    switch (data.code) {
      case HTTP_STATUS.UNAUTHORIZED:
        await handleUnauthorized();
        break;
      case HTTP_STATUS.FORBIDDEN:
        ElMessage.error("权限不足");
        break;
      case HTTP_STATUS.NOT_FOUND:
        ElMessage.error("请求的资源不存在");
        break;
      case HTTP_STATUS.TOO_MANY_REQUESTS:
        ElMessage.error("请求过于频繁，请稍后再试");
        break;
      case HTTP_STATUS.INTERNAL_SERVER_ERROR:
        ElMessage.error("服务器内部错误");
        break;
      default:
        ElMessage.error(errorMessage);
    }

    return Promise.reject(new Error(errorMessage));
  },
  async (error) => {
    const appStore = useAppStore();
    appStore.setLoading(false);

    console.error("❌ API响应错误:", error);

    let errorMessage = "网络错误";

    if (error.response) {
      const { status, data } = error.response;

      switch (status) {
        case HTTP_STATUS.BAD_REQUEST:
          errorMessage = data?.message || "请求参数错误";
          break;
        case HTTP_STATUS.UNAUTHORIZED:
          await handleUnauthorized();
          return Promise.reject(error);
        case HTTP_STATUS.FORBIDDEN:
          errorMessage = "权限不足";
          break;
        case HTTP_STATUS.NOT_FOUND:
          errorMessage = "请求的资源不存在";
          break;
        case 408:
          errorMessage = "请求超时";
          break;
        case HTTP_STATUS.TOO_MANY_REQUESTS:
          errorMessage = "请求过于频繁，请稍后再试";
          break;
        case HTTP_STATUS.INTERNAL_SERVER_ERROR:
          errorMessage = "服务器内部错误";
          break;
        case HTTP_STATUS.BAD_GATEWAY:
          errorMessage = "网关错误";
          break;
        case HTTP_STATUS.SERVICE_UNAVAILABLE:
          errorMessage = "服务暂时不可用";
          break;
        case HTTP_STATUS.GATEWAY_TIMEOUT:
          errorMessage = "网关超时";
          break;
        default:
          errorMessage = data?.message || `请求失败 (${status})`;
      }
    } else if (error.request) {
      if (error.code === "ECONNABORTED") {
        errorMessage = "请求超时，请检查网络连接";
      } else if (error.code === "ERR_NETWORK") {
        errorMessage = "网络连接失败，请检查网络设置";
      } else {
        errorMessage = "网络错误，请稍后重试";
      }
    } else {
      errorMessage = error.message || "未知错误";
    }

    ElMessage.error(errorMessage);
    return Promise.reject(error);
  },
);

// 处理未授权错误
const handleUnauthorized = async () => {
  const userStore = useUserStore();

  // 尝试刷新token
  if (userStore.refreshToken) {
    try {
      await userStore.refreshAccessToken();
      return;
    } catch {
      // 刷新token失败，忽略错误
    }
  }

  // 清除用户状态并跳转到登录页
  await userStore.logout();

  ElMessageBox.alert("登录已过期，请重新登录", "提示", {
    confirmButtonText: "确定",
    type: "warning",
  }).then(() => {
    router.push({
      name: "Login",
      query: { redirect: router.currentRoute.value.fullPath },
    });
  });
};

// 扩展AxiosRequestConfig类型
declare module "axios" {
  interface AxiosRequestConfig {
    showLoading?: boolean;
    loadingText?: string;
  }
}

// 导出请求方法
export const request = {
  get<T = any>(
    url: string,
    params?: any,
    config?: AxiosRequestConfig,
  ): Promise<T> {
    return service.get(url, { params, ...config });
  },

  post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig,
  ): Promise<T> {
    return service.post(url, data, config);
  },

  put<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig,
  ): Promise<T> {
    return service.put(url, data, config);
  },

  patch<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig,
  ): Promise<T> {
    return service.patch(url, data, config);
  },

  delete<T = any>(
    url: string,
    params?: any,
    config?: AxiosRequestConfig,
  ): Promise<T> {
    return service.delete(url, { params, ...config });
  },

  upload<T = any>(
    url: string,
    formData: FormData,
    config?: AxiosRequestConfig,
  ): Promise<T> {
    return service.post(url, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
      ...config,
    });
  },

  download(url: string, params?: any, filename?: string): Promise<void> {
    return service
      .get(url, {
        params,
        responseType: "blob",
        showLoading: true,
        loadingText: "下载中...",
      })
      .then((response: any) => {
        const blob = new Blob([response]);
        const downloadUrl = window.URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = filename || `download_${Date.now()}`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(downloadUrl);
      });
  },
};

// 导出axios实例
export default service;

// 导出类型
export type { AxiosRequestConfig, AxiosResponse };
